package com.zbu.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zbu.common.core.constants.Constants;
import com.zbu.common.core.constants.HttpConstants;
import com.zbu.common.core.utils.ThreadLocalUtil;
import com.zbu.common.security.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.locks.Condition;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private TokenService tokenService;//从哪个服务的容器进行管理就从哪个配置中拿取
    @Value("${jwt.secret}")
    private String secret;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=getToken(request);
        if(StrUtil.isEmpty(token)){
            return true;
        }
        Claims claims=tokenService.getClaims(token,secret);
        Long userId = tokenService.getUserId(token, secret);
        String userKey = tokenService.getUserKey(claims);
        ThreadLocalUtil.set(Constants.USER_ID,userId);
        ThreadLocalUtil.set(Constants.USER_KEY,userKey);
        tokenService.extendToken(claims);
        return true;
    }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
    private String getToken(HttpServletRequest request){
        String token=request.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token)&&token.startsWith(HttpConstants.PREFIX)){
            token=token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;
    }
}
